
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>条件表达式 &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="数据库函数" href="database-functions.html" />
    <link rel="prev" title="查询表达式" href="expressions.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="expressions.html" title="查询表达式">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="database-functions.html" title="数据库函数">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-models-conditional-expressions">
            
  <div class="section" id="s-conditional-expressions">
<span id="conditional-expressions"></span><h1>条件表达式<a class="headerlink" href="#conditional-expressions" title="永久链接至标题">¶</a></h1>
<p>条件表达式让你可以在过滤器、注解、聚合和更新中使用 <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#if" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> ... <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#elif" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a> ... <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#else" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> 逻辑。条件表达式对表的每条记录执行一系列条件，并返回匹配的结果表达式。条件表达式也可以像其他 <a class="reference internal" href="expressions.html"><span class="doc">表达式</span></a> 一样进行组合和嵌套。</p>
<div class="section" id="s-the-conditional-expression-classes">
<span id="the-conditional-expression-classes"></span><h2>条件表达式类<a class="headerlink" href="#the-conditional-expression-classes" title="永久链接至标题">¶</a></h2>
<p>在后续的例子中，我们将使用以下模型：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Client</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">REGULAR</span> <span class="o">=</span> <span class="s1">&#39;R&#39;</span>
    <span class="n">GOLD</span> <span class="o">=</span> <span class="s1">&#39;G&#39;</span>
    <span class="n">PLATINUM</span> <span class="o">=</span> <span class="s1">&#39;P&#39;</span>
    <span class="n">ACCOUNT_TYPE_CHOICES</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="n">REGULAR</span><span class="p">,</span> <span class="s1">&#39;Regular&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="n">GOLD</span><span class="p">,</span> <span class="s1">&#39;Gold&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="n">PLATINUM</span><span class="p">,</span> <span class="s1">&#39;Platinum&#39;</span><span class="p">),</span>
    <span class="p">]</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">registered_on</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">account_type</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span>
        <span class="n">max_length</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
        <span class="n">choices</span><span class="o">=</span><span class="n">ACCOUNT_TYPE_CHOICES</span><span class="p">,</span>
        <span class="n">default</span><span class="o">=</span><span class="n">REGULAR</span><span class="p">,</span>
    <span class="p">)</span>
</pre></div>
</div>
<div class="section" id="s-when">
<span id="when"></span><h3><code class="docutils literal notranslate"><span class="pre">When</span></code><a class="headerlink" href="#when" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.expressions.When">
<em class="property">class </em><code class="descname">When</code>(<em>condition=None</em>, <em>then=None</em>, <em>**lookups</em>)<a class="headerlink" href="#django.db.models.expressions.When" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">When()</span></code> 对象用于封装一个条件及其结果，以便在条件表达式中使用。使用 <code class="docutils literal notranslate"><span class="pre">When()</span></code> 对象类似于使用 <a class="reference internal" href="querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> 方法。可以使用 <a class="reference internal" href="querysets.html#field-lookups"><span class="std std-ref">字段查找</span></a>、 <a class="reference internal" href="querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span></code></a> 对象或 <a class="reference internal" href="expressions.html#django.db.models.Expression" title="django.db.models.Expression"><code class="xref py py-class docutils literal notranslate"><span class="pre">Expression</span></code></a> 对象来指定条件，这些对象的 <cite>output_field</cite> 是 <a class="reference internal" href="fields.html#django.db.models.BooleanField" title="django.db.models.BooleanField"><code class="xref py py-class docutils literal notranslate"><span class="pre">BooleanField</span></code></a>。结果是用 <code class="docutils literal notranslate"><span class="pre">then</span></code> 关键字提供的。</p>
<p>一些例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">F</span><span class="p">,</span> <span class="n">Q</span><span class="p">,</span> <span class="n">When</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># String arguments refer to fields; the following two examples are equivalent:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">When</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">GOLD</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">When</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">GOLD</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># You can use field lookups in the condition</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">date</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">When</span><span class="p">(</span><span class="n">registered_on__gt</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2014</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>     <span class="n">registered_on__lt</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2015</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>     <span class="n">then</span><span class="o">=</span><span class="s1">&#39;account_type&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Complex conditions can be created using Q objects</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">When</span><span class="p">(</span><span class="n">Q</span><span class="p">(</span><span class="n">name__startswith</span><span class="o">=</span><span class="s2">&quot;John&quot;</span><span class="p">)</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">name__startswith</span><span class="o">=</span><span class="s2">&quot;Paul&quot;</span><span class="p">),</span>
<span class="gp">... </span>     <span class="n">then</span><span class="o">=</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Condition can be created using boolean expressions.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">Exists</span><span class="p">,</span> <span class="n">OuterRef</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">non_unique_account_type</span> <span class="o">=</span> <span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">OuterRef</span><span class="p">(</span><span class="s1">&#39;account_type&#39;</span><span class="p">),</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">OuterRef</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">))</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">When</span><span class="p">(</span><span class="n">Exists</span><span class="p">(</span><span class="n">non_unique_account_type</span><span class="p">),</span> <span class="n">then</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;non unique&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>请记住，每个值都可以是一个表达式。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>由于 <code class="docutils literal notranslate"><span class="pre">then</span></code> 关键字参数是为 <code class="docutils literal notranslate"><span class="pre">When()</span></code> 的结果保留的，所以如果一个 <a class="reference internal" href="instances.html#django.db.models.Model" title="django.db.models.Model"><code class="xref py py-class docutils literal notranslate"><span class="pre">Model</span></code></a> 有一个名为 <code class="docutils literal notranslate"><span class="pre">then</span></code> 的字段，就会有潜在的冲突。这可以通过两种方式解决：</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">When</span><span class="p">(</span><span class="n">then__exact</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">When</span><span class="p">(</span><span class="n">Q</span><span class="p">(</span><span class="n">then</span><span class="o">=</span><span class="mi">0</span><span class="p">),</span> <span class="n">then</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>Support for using the <code class="docutils literal notranslate"><span class="pre">condition</span></code> argument with <code class="docutils literal notranslate"><span class="pre">lookups</span></code> was added.</p>
</div>
</div>
<div class="section" id="s-case">
<span id="case"></span><h3><code class="docutils literal notranslate"><span class="pre">Case</span></code><a class="headerlink" href="#case" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.expressions.Case">
<em class="property">class </em><code class="descname">Case</code>(<em>*cases</em>, <em>**extra</em>)<a class="headerlink" href="#django.db.models.expressions.Case" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">Case()</span></code> 表达式就像 <code class="docutils literal notranslate"><span class="pre">Python</span></code> 中的 <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#if" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>... <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#elif" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a>... <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#else" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> 语句。在提供的 <code class="docutils literal notranslate"><span class="pre">When()</span></code> 对象中的每个 <code class="docutils literal notranslate"><span class="pre">condition</span></code> 按顺序执行，直到执行出一个对的值。从匹配的 <code class="docutils literal notranslate"><span class="pre">When()</span></code> 对象中返回 <code class="docutils literal notranslate"><span class="pre">result</span></code> 表达式。</p>
<p>一个例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">date</span><span class="p">,</span> <span class="n">timedelta</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">Case</span><span class="p">,</span> <span class="n">Value</span><span class="p">,</span> <span class="n">When</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;Jane Doe&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">REGULAR</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">registered_on</span><span class="o">=</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">36</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;James Smith&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">GOLD</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">registered_on</span><span class="o">=</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">5</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;Jack Black&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">PLATINUM</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">registered_on</span><span class="o">=</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">10</span> <span class="o">*</span> <span class="mi">365</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Get the discount for each Client based on the account type</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">discount</span><span class="o">=</span><span class="n">Case</span><span class="p">(</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">GOLD</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;5%&#39;</span><span class="p">)),</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">PLATINUM</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;10%&#39;</span><span class="p">)),</span>
<span class="gp">... </span>        <span class="n">default</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;0%&#39;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="p">),</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;discount&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [(&#39;Jane Doe&#39;, &#39;0%&#39;), (&#39;James Smith&#39;, &#39;5%&#39;), (&#39;Jack Black&#39;, &#39;10%&#39;)]&gt;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">Case()</span></code> 接受任意数量的 <code class="docutils literal notranslate"><span class="pre">When()</span></code> 对象作为单个参数。其他选项是通过关键字参数提供的。如果没有一个条件的值是 <code class="docutils literal notranslate"><span class="pre">TRUE</span></code>，那么将返回用 <code class="docutils literal notranslate"><span class="pre">default</span></code> 关键字参数给出的表达式。如果没有提供 <code class="docutils literal notranslate"><span class="pre">default</span></code> 参数，则使用 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
<p>如果我们想改变之前的查询，根据 <code class="docutils literal notranslate"><span class="pre">Client</span></code> 与我们合作的时间长短来获取折扣，我们可以使用查找：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_month_ago</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_year_ago</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">365</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Get the discount for each Client based on the registration date</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">discount</span><span class="o">=</span><span class="n">Case</span><span class="p">(</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">registered_on__lte</span><span class="o">=</span><span class="n">a_year_ago</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;10%&#39;</span><span class="p">)),</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">registered_on__lte</span><span class="o">=</span><span class="n">a_month_ago</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;5%&#39;</span><span class="p">)),</span>
<span class="gp">... </span>        <span class="n">default</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;0%&#39;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="p">)</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;discount&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [(&#39;Jane Doe&#39;, &#39;5%&#39;), (&#39;James Smith&#39;, &#39;0%&#39;), (&#39;Jack Black&#39;, &#39;10%&#39;)]&gt;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">请记住，条件是按顺序计算的，所以在上面的例子中，尽管第二个条件同时符合 Jane Doe 和 Jack Black，我们还是得到了正确的结果。这就像在 <code class="docutils literal notranslate"><span class="pre">Python</span></code> 中的 <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#if" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>... <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#elif" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a>... <a class="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#else" title="(在 Python v3.9)"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> 语句一样。</p>
</div>
<p><code class="docutils literal notranslate"><span class="pre">Case()</span></code> 也可以在 <code class="docutils literal notranslate"><span class="pre">filter()</span></code> 子句中使用。例如，要查找一个月前注册的黄金客户和一年前注册的白金客户：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_month_ago</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_year_ago</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">365</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">registered_on__lte</span><span class="o">=</span><span class="n">Case</span><span class="p">(</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">GOLD</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="n">a_month_ago</span><span class="p">),</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">PLATINUM</span><span class="p">,</span> <span class="n">then</span><span class="o">=</span><span class="n">a_year_ago</span><span class="p">),</span>
<span class="gp">... </span>    <span class="p">),</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;account_type&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [(&#39;Jack Black&#39;, &#39;P&#39;)]&gt;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-advanced-queries">
<span id="advanced-queries"></span><h2>高级查询<a class="headerlink" href="#advanced-queries" title="永久链接至标题">¶</a></h2>
<p>条件表达式可用于注解、聚合、过滤器、查找和更新中。它们还可以与其他表达式组合和嵌套。这使你可以进行强大的条件查询。</p>
<div class="section" id="s-conditional-update">
<span id="conditional-update"></span><h3>条件更新<a class="headerlink" href="#conditional-update" title="永久链接至标题">¶</a></h3>
<p>比方说，我们想改变客户的 <code class="docutils literal notranslate"><span class="pre">account_type</span></code> 以匹配他们的注册日期。我们可以使用一个条件表达式和 <a class="reference internal" href="querysets.html#django.db.models.query.QuerySet.update" title="django.db.models.query.QuerySet.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> 方法来实现这个目标：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_month_ago</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_year_ago</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">365</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Update the account_type for each Client from the registration date</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">Case</span><span class="p">(</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">registered_on__lte</span><span class="o">=</span><span class="n">a_year_ago</span><span class="p">,</span>
<span class="gp">... </span>             <span class="n">then</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="n">Client</span><span class="o">.</span><span class="n">PLATINUM</span><span class="p">)),</span>
<span class="gp">... </span>        <span class="n">When</span><span class="p">(</span><span class="n">registered_on__lte</span><span class="o">=</span><span class="n">a_month_ago</span><span class="p">,</span>
<span class="gp">... </span>             <span class="n">then</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="n">Client</span><span class="o">.</span><span class="n">GOLD</span><span class="p">)),</span>
<span class="gp">... </span>        <span class="n">default</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="n">Client</span><span class="o">.</span><span class="n">REGULAR</span><span class="p">)</span>
<span class="gp">... </span>    <span class="p">),</span>
<span class="gp">... </span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;account_type&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [(&#39;Jane Doe&#39;, &#39;G&#39;), (&#39;James Smith&#39;, &#39;R&#39;), (&#39;Jack Black&#39;, &#39;P&#39;)]&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-conditional-aggregation">
<span id="s-id1"></span><span id="conditional-aggregation"></span><span id="id1"></span><h3>条件聚合<a class="headerlink" href="#conditional-aggregation" title="永久链接至标题">¶</a></h3>
<p>如果我们想知道每个 <code class="docutils literal notranslate"><span class="pre">account_type</span></code> 有多少个客户？我们可以使用 <a class="reference internal" href="querysets.html#aggregation-functions"><span class="std std-ref">聚合函数</span></a> 的 <code class="docutils literal notranslate"><span class="pre">filter</span></code> 参数来实现：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Create some more Clients first so we can have something to count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;Jean Grey&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">REGULAR</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">registered_on</span><span class="o">=</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;James Bond&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">PLATINUM</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">registered_on</span><span class="o">=</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;Jane Porter&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">PLATINUM</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">registered_on</span><span class="o">=</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Get counts for each value of account_type</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">Count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">aggregate</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">regular</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">,</span> <span class="nb">filter</span><span class="o">=</span><span class="n">Q</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">REGULAR</span><span class="p">)),</span>
<span class="gp">... </span>    <span class="n">gold</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">,</span> <span class="nb">filter</span><span class="o">=</span><span class="n">Q</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">GOLD</span><span class="p">)),</span>
<span class="gp">... </span>    <span class="n">platinum</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">,</span> <span class="nb">filter</span><span class="o">=</span><span class="n">Q</span><span class="p">(</span><span class="n">account_type</span><span class="o">=</span><span class="n">Client</span><span class="o">.</span><span class="n">PLATINUM</span><span class="p">)),</span>
<span class="gp">... </span><span class="p">)</span>
<span class="go">{&#39;regular&#39;: 2, &#39;gold&#39;: 1, &#39;platinum&#39;: 3}</span>
</pre></div>
</div>
<p>在支持 SQL 2003 <code class="docutils literal notranslate"><span class="pre">FILTER</span> <span class="pre">WHERE</span></code> 语法的数据库上，这个聚合产生一个查询。</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="k">count</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span> <span class="n">FILTER</span> <span class="p">(</span><span class="k">WHERE</span> <span class="n">account_type</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="k">as</span> <span class="n">regular</span><span class="p">,</span>
       <span class="k">count</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span> <span class="n">FILTER</span> <span class="p">(</span><span class="k">WHERE</span> <span class="n">account_type</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="k">as</span> <span class="n">gold</span><span class="p">,</span>
       <span class="k">count</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span> <span class="n">FILTER</span> <span class="p">(</span><span class="k">WHERE</span> <span class="n">account_type</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="k">as</span> <span class="n">platinum</span>
<span class="k">FROM</span> <span class="n">clients</span><span class="p">;</span>
</pre></div>
</div>
<p>在其他数据库中，这是用 <code class="docutils literal notranslate"><span class="pre">CASE</span></code> 语句模拟的：</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="k">count</span><span class="p">(</span><span class="k">CASE</span> <span class="k">WHEN</span> <span class="n">account_type</span><span class="o">=</span><span class="mi">1</span> <span class="k">THEN</span> <span class="n">id</span> <span class="k">ELSE</span> <span class="k">null</span><span class="p">)</span> <span class="k">as</span> <span class="n">regular</span><span class="p">,</span>
       <span class="k">count</span><span class="p">(</span><span class="k">CASE</span> <span class="k">WHEN</span> <span class="n">account_type</span><span class="o">=</span><span class="mi">2</span> <span class="k">THEN</span> <span class="n">id</span> <span class="k">ELSE</span> <span class="k">null</span><span class="p">)</span> <span class="k">as</span> <span class="n">gold</span><span class="p">,</span>
       <span class="k">count</span><span class="p">(</span><span class="k">CASE</span> <span class="k">WHEN</span> <span class="n">account_type</span><span class="o">=</span><span class="mi">3</span> <span class="k">THEN</span> <span class="n">id</span> <span class="k">ELSE</span> <span class="k">null</span><span class="p">)</span> <span class="k">as</span> <span class="n">platinum</span>
<span class="k">FROM</span> <span class="n">clients</span><span class="p">;</span>
</pre></div>
</div>
<p>这两条 SQL 语句在功能上是等同的，但更明确的 <code class="docutils literal notranslate"><span class="pre">FILTER</span></code> 可能表现得更好。</p>
</div>
<div class="section" id="s-conditional-filter">
<span id="conditional-filter"></span><h3>条件过滤<a class="headerlink" href="#conditional-filter" title="永久链接至标题">¶</a></h3>
<p>当条件表达式返回一个布尔值时，可以直接在过滤器中使用它。这意味着它不会被添加到 <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> 列中，但你仍然可以使用它来过滤结果：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">non_unique_account_type</span> <span class="o">=</span> <span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">account_type</span><span class="o">=</span><span class="n">OuterRef</span><span class="p">(</span><span class="s1">&#39;account_type&#39;</span><span class="p">),</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">OuterRef</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">))</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Client</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="o">~</span><span class="n">Exists</span><span class="p">(</span><span class="n">non_unique_account_type</span><span class="p">))</span>
</pre></div>
</div>
<p>用 SQL 术语来说，它的值是：</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="p">...</span>
<span class="k">FROM</span> <span class="n">client</span> <span class="n">c0</span>
<span class="k">WHERE</span> <span class="k">NOT</span> <span class="k">EXISTS</span> <span class="p">(</span>
  <span class="k">SELECT</span> <span class="n">c1</span><span class="p">.</span><span class="n">id</span>
  <span class="k">FROM</span> <span class="n">client</span> <span class="n">c1</span>
  <span class="k">WHERE</span> <span class="n">c1</span><span class="p">.</span><span class="n">account_type</span> <span class="o">=</span> <span class="n">c0</span><span class="p">.</span><span class="n">account_type</span> <span class="k">AND</span> <span class="k">NOT</span> <span class="n">c1</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">c0</span><span class="p">.</span><span class="n">id</span>
<span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">条件表达式</a><ul>
<li><a class="reference internal" href="#the-conditional-expression-classes">条件表达式类</a><ul>
<li><a class="reference internal" href="#when"><code class="docutils literal notranslate"><span class="pre">When</span></code></a></li>
<li><a class="reference internal" href="#case"><code class="docutils literal notranslate"><span class="pre">Case</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#advanced-queries">高级查询</a><ul>
<li><a class="reference internal" href="#conditional-update">条件更新</a></li>
<li><a class="reference internal" href="#conditional-aggregation">条件聚合</a></li>
<li><a class="reference internal" href="#conditional-filter">条件过滤</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="expressions.html"
                        title="上一章">查询表达式</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="database-functions.html"
                        title="下一章">数据库函数</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/models/conditional-expressions.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="expressions.html" title="查询表达式">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="database-functions.html" title="数据库函数">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>